<template>
	<view class="login">

		<!-- #ifdef MP-WEIXIN -->
		<view class="mpwx-login">
			<image class="logo" :src="appConfig.shop_login_logo"></image>
			<button size="lg" class="white br5 row-center btn" @click="loginMP_WEIXIN">
				<!-- <image class="mr10 image" src="/static/images/icon_wechat.png"></image> -->
				<text>用户一键登录</text>
			</button>
			<view class="radio" @click="change">
				<radio class="select" :checked="agreement" color="#ff0000"></radio>
				<view class="labelText">
					<text>我已阅读并同意</text>
					<text @click.stop="goToExplain(0)">《服务协议》</text>
					<text>和</text>
					<text @click.stop="goToExplain(1)">《隐私协议》</text>
				</view>
			</view>
			<!-- <view class="avatar">
				<open-data type="userAvatarUrl"></open-data>
			</view>
			<view class="user-name mt20">
				<open-data type="userNickName"></open-data>
			</view>
			<view class="title xxl mt20 bold">微信授权登录</view>
			<button size="lg" class="white br60 row-center btn" @click="loginMP_WEIXIN">
				<image class="mr10 image" src="/static/images/icon_wechat.png"></image>
				<text>微信一键授权</text>
			</button>
			<view class="muted mt20">微信授权登录后才可进行更多操作哦</view> -->
		</view>
		<mplogin-popup v-model="showLoginPop" :logo="appConfig.shop_login_logo" :title="appConfig.name"
			@close="closePopup" @update="handleSubmitInfo" />
		<!--  #endif -->
	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	import {
		accountLogin,
		codeLogin,
		sendSms,
		wxpLogin,
		smsCodeLogin,
		opLogin,
		authLogin,
		updateUser
	} from '@/api/app';

	import {
		inputInviteCode
	} from '@/api/user'

	import wechath5 from '@/utils/wechath5'

	import {
		isWeixinClient,
		currentPage,
		client
	} from '@/utils/tools'

	import {
		SMSType
	} from "@/utils/type"

	import Cache from "@/utils/cache"

	import {
		BACK_URL,
		INVITE_CODE
	} from '@/config/cachekey'

	import {
		getWxCode,
		getUserProfile
	} from '@/utils/login'
	import cachekey from '../../config/cachekey';

	const loginType = {
		ACCOUNT_LOGIN: 0,
		SMS_CODE_LOGIN: 1,
	}

	export default {
		data() {
			return {
				password: '',
				account: '',
				code: '',
				isWeixin: '',
				loginType: 0,
				smsCode: '',
				time: 59,
				canSendSms: true,
				telephone: "",
				showLoginPop: false,
				agreement: false
			}
		},

		computed: {
			...mapGetters(['appConfig'])
		},

		methods: {
			...mapMutations(['LOGIN']),
			...mapActions(['getUser']),

			countDownFinish() {
				this.canSendSms = true;
			},

			//同意/不同意政策
			async change() {
				this.agreement = !this.agreement
			},
			goToExplain(value) {
				uni.navigateTo({
					url: '/bundle/pages/server_explan/server_explan?type=' + value
				})
			},


			onAuthError() {
				console.log('Auth Error ....');
			},

			// 微信小程序登录
			async loginMP_WEIXIN() {
				if (this.agreement == false) {
					this.$toast({
						title: '请阅读并同意《服务协议》和《隐私协议》'
					})
					return
				}
				// 获取用户信息
				const {
					userInfo
				} = await getUserProfile()
				// 获取用户授权码
				const wxCode = await getWxCode()

				uni.showLoading({
					title: '登录中...',
					mask: true,
				})
				const invite_code = Cache.get(cachekey.INVITE_CODE) || '';
				// 登录处理
				authLogin({
					code: wxCode,
					nickname: userInfo.nickName,
					headimgurl: userInfo.avatarUrl,
					invite_code
				}).then(({
					code,
					data,
					msg
				}) => {
					if (code !== 1) throw msg
					if (data.is_new_user) {
						uni.hideLoading();
						this.showLoginPop = true;
						this.loginData = data;
					} else {
						this.loginHandle(data);
					}
				}).catch(errMsg => {
					this.$toast({
						title: errMsg
					})
				})
			},

			// 账号登录
			async loginFun() {
				const {
					account,
					password,
					telephone,
					smsCode
				} = this
				if (this.loginType == 0) {
					const {
						code,
						data
					} = await accountLogin({
						account,
						password,
						client: client
					})
					if (code == 1) {
						this.loginHandle(data)
					}
				} else {
					if (!telephone) {
						this.$toast({
							title: '请填写手机号'
						});
						return;
					}
					if (!smsCode) {
						this.$toast({
							title: '请填写手机验证码'
						});
						return;
					}
					smsCodeLogin({
						account: telephone,
						code: smsCode,
					}).then(res => {
						if (res.code == 1) {
							this.loginHandle(res.data)
						}
					})
				}
			},

			// 登录结果处理
			async loginHandle(data) {
				console.log(data);
				this.LOGIN(data)
				const inviteCode = Cache.get(INVITE_CODE)
				if (inviteCode) {
					inputInviteCode({
						code: inviteCode
					})
				}
				uni.hideLoading()
				// #ifdef H5
				location.replace('/mobile' + (Cache.get(BACK_URL) || '/'))
				Cache.remove(BACK_URL)
				//#endif
				// #ifdef MP-WEIXIN  || APP-PLUS || MP-ALIPAY
				uni.navigateBack({
					success() {
						// 刷新上一页
						const {
							onLoad,
							options
						} = currentPage()
						onLoad && onLoad(options)
					}
				})
				//#endif

			},

			changeLoginType() {
				if (this.loginType == loginType.ACCOUNT_LOGIN) {
					this.loginType = loginType.SMS_CODE_LOGIN
				} else if (this.loginType == loginType.SMS_CODE_LOGIN) {
					this.loginType = loginType.ACCOUNT_LOGIN
				}
			},

			// 发送验证码
			$sendSms() {
				if (this.canSendSms == false) {
					return;
				}
				if (!this.telephone) {
					this.$toast({
						title: '请填写手机号信息～'
					})
					return;
				}

				sendSms({
					mobile: this.telephone,
					key: SMSType.LOGIN
				}).then(res => {
					if (res.code == 1) {
						this.canSendSms = false;
						this.$refs.countDown.start();
						this.$toast({
							title: res.msg
						});
					}
				})
			},
			async handleSubmitInfo(e) {
				const loginData = this.loginData || {};
				const res = await updateUser(e, loginData.token);
				if (res.code == 1) {
					this.loginHandle(loginData);
				}
			},
			closePopup() {
				this.showLoginPop = false;
			},
		},

		async onLoad(option) {
			// #ifdef H5
			// H5微信登录
			this.isWeixin = isWeixinClient()
			if (this.isLogin) {
				uni.switchTab({
					url: '/pages/index/index'
				})
				return
			}
			if (this.isWeixin) {
				const {
					code
				} = option
				if (code) {
					const data = await wechath5.authLogin(code)
					this.loginHandle(data)
				} else {
					wechath5.getWxUrl()
				}
			}
			// #endif
		},
	}
</script>
<style lang="scss" scoped>
	page {
		background: url('/static/images/login_bg.png');
		text-align: center;

		.login {
			height: 100vh;

			.mpwx-login {
				height: 100%;
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;

				.logo {
					height: 92rpx;
					margin-top: 195rpx;
					width: 344rpx;
				}

				.radio {
					display: flex;
					justify-content: center;
					align-items: center;
					margin-top: 40rpx;

					.select {
						color: #ff0000 !important;
					}

					.labelText {
						text {
							&:nth-of-type(2n) {
								color: #ff0000;
							}

							&:nth-of-type(2n+1) {
								color: #666666;
							}
						}
					}
				}

				// .avatar {
				// 	display: inline-block;
				// 	width: 120rpx;
				// 	height: 120rpx;
				// 	border-radius: 50%;
				// 	border: 1px solid #eee;
				// 	overflow: hidden;
				// }

				// .user-name {
				// 	height: 40rpx;
				// }

				// .image {
				// 	width: 50rpx;
				// 	height: 50rpx;
				// }

				.btn {
					background-color: #FF2C3C;
					width: 580rpx;
					margin: 80rpx auto 0;
				}
			}


			.h5-login {
				padding-top: 100rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				height: 100%;
				box-sizing: border-box;

				.logo {
					width: 280rpx;
					height: 80rpx;
					margin-bottom: 50rpx;
				}

				.input {
					width: 670rpx;
					border-bottom: $-solid-border;
					margin-top: 30rpx;
				}

				.sms-btn {
					border: 1px solid $-color-primary;
					width: 176rpx;
					height: 60rpx;
					box-sizing: border-box;
				}

				.wx-login {
					margin-top: 60rpx;

					.image {
						margin-top: 40rpx;
						width: 80rpx;
						height: 80rpx;
					}
				}
			}
		}

		.alipay-button--login {
			height: 80rpx;
			line-height: 80rpx;
			background-color: #1677ff !important;
		}
	}

	.uni-checkbox-input-checked,
	.uni-radio-input-checked,
	.uni-switch-input-checked {
		background-color: #5FB878 !important;
		border-color: #5FB878 !important;
		color: #fff !important;
	}
</style>